/* Author: Tobin Bradley
*/


var selected_filename = '';
var map;
var untiled;
var tiled;
var pureCoverage = false;
// pink tile avoidance
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
// make OL compute scale according to WMS spec
OpenLayers.DOTS_PER_INCH = 25.4 / 0.28;
			
			

/**
 *Ye olde browser ready functioning. All the crud that needs to set the page up on
 *first load happens here.
 */
 $(document).ready(function() {
	 
	 // Get Latest
	 $("#latest_updates").load("services/ws_metadata_latest.php?format=html");

	 // Detect arguments
     if (getUrlVars()["search"]) {
		loadMeta(getUrlVars()["search"]);
	}
	
	
	$("form").submit(function(){
		url = "services/ws_metadata_search.php?format=json&search=" + $('#searchtext').val() + "&field=";
        $.getJSON(url, function(data) {
			$returnHTML = "";
			if (data.total_rows > 0 ) {						  
				$.each(data.rows, function(i, item){                        
					thelink = "loadMeta('" + urlencode(item.row.file_name) +"');";
					$returnHTML += '<a href="javascript:void(0);" onclick="' + thelink + '" class="searchlinks"> ' + urldecode(item.row.title) + '</a><p>' + trunc(urldecode(item.row.abstract)) + '</p>';
				});
			}
			else {
				$returnHTML += "<h1>Dang it!</h1> Didn't find anything.";
			}
			$("#metadataselector").hide();
			$('#main-content').html($returnHTML);
		});
	});
	
	
});



function loadMeta(thefilename) {
    selected_filename = thefilename;
	$("#metadataselector").show();
    $("#xmllink").attr("href", "services/ws_metadata_search.php?format=raw&field=&search=" + thefilename);  
	
	// The magic
	$("#main-content").load("services/ws_metadata_search.php?format=summary&field=&search=" + selected_filename);
}

function changeMeta(xslname) {
	$("#main-content").load("services/ws_metadata_search.php?format=" + xslname + "&field=&search=" + selected_filename);
}


/**
 * Truncate string to 100 chars and add elipses
 */
function trunc(thestring) {
	if (thestring.length <= 200 ) {
		return thestring;
	}
	else {
		return thestring.substring(0,197) + "...";
	}	
}


/**
 * Takes a string a URL encodes it
 * @param {string} str
 */
function urlencode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}

/**
 * Decodes a url encoded string
 * @param {string} str
 */
function urldecode(str) {
	str = unescape(str);
     str = str.replace(/\+/g, ' ');
	return str;
}


/**
 * Validate the URL is a URL and contains WMS
 */
function isValidWMSURL(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	if (regexp.test(s) && s.toUpperCase().match('WMS')) {
		return true;
	}
	else {
		return false;
	}
}

/**
 * Get URL args
 */
function gup( name, url )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url.toLowerCase() );
  if( results == null )
    return "";
  else
    return results[1];
}


function map_init(wmsurl){
	if (isValidWMSURL(wmsurl)) {
		$("#map").show();
		$("#nodelist").show();
		// Set variables from URL argumemts
		wmsurl = urldecode(wmsurl);
		//main url
		wmsbaseurl = wmsbaseurl = wmsurl.slice(0, wmsurl.indexOf("?"));
		//layername
		layername = gup('layers', wmsurl);
		//bounding box
		bbox = gup("bbox", wmsurl).split(",");
		// projection
		epsg = gup("srs", wmsurl);
		// style
		sld = gup("style", wmsurl);
		// call mapgen
		mapgen(wmsbaseurl,layername,bbox, epsg, sld);
		
	}
	else {
		$("#map").hide();
		$("#nodelist").hide();
	}
}

function mapgen(wmsurl, layername, bbox, epsg, sld) {
	
	// if this is just a coverage or a group of them, disable a few items,
	// and default to jpeg format
	format = 'image/png';

	var bounds = new OpenLayers.Bounds(
		parseFloat(bbox[0]), parseFloat(bbox[1]),
		parseFloat(bbox[2]), parseFloat(bbox[3])
	);
	var options = {
		controls: [],
		maxExtent: bounds,
		maxResolution: 882.7348803710936,
		projection: epsg,
		units: 'm'
	};
	map = new OpenLayers.Map('map', options);


	// setup single tiled layer
	untiled = new OpenLayers.Layer.WMS(
		layername, wmsurl,
		{
			srs: epsg,
			layers: layername,	
			styles: sld,
			format: format
		},
		{singleTile: true, ratio: 1} 
	);

	map.addLayers([untiled]);

	// build up all controls            
	map.addControl(new OpenLayers.Control.PanZoom());
	map.addControl(new OpenLayers.Control.Navigation());
	map.addControl(new OpenLayers.Control.Scale());
	map.addControl(new OpenLayers.Control.MousePosition());
	
	map.zoomToExtent(bounds);
	

	// support GetFeatureInfo
	map.events.register('click', map, function (e) {
		document.getElementById('nodelist').innerHTML = "Loading... please wait...";
		var params = {
			REQUEST: "GetFeatureInfo",
			EXCEPTIONS: "application/vnd.ogc.se_xml",
			BBOX: map.getExtent().toBBOX(),
			X: e.xy.x,
			Y: e.xy.y,
			INFO_FORMAT: 'text/html',
			QUERY_LAYERS: map.layers[0].params.LAYERS,
			FEATURE_COUNT: 50,
			Srs: epsg,
			Layers: layername,
			Styles: '',
			WIDTH: map.size.w,
			HEIGHT: map.size.h,
			format: format};
		$.get("services/ws_wms_query_proxy.php", params, function(data) {
			$("#nodelist").html(data);
			});
		OpenLayers.Event.stop(e);
	});
}




/**
 * Read a page's GET URL variables and return them as an associative array.
 */
function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}



















